//
//  LC ZTLCCamera.m
//  YSSmartHome
//
//  Created by yanghao on 2016/9/26.
//  Copyright © 2016年 yahaong. All rights reserved.
//

#import "ZTLCCamera.h"
#import "DataManager.h"
#import "ZTLCCameraUtil.h"
#import "openApiService.h"
#import "LCOpenSDK_Api.h"
#import "RestApiService.h"

static NSString *const svrStr = @"openapi.lechange.cn";
static NSInteger const iPort = 443;
static NSString *const appIdStr = @"lc1636ff487bc74a3e";
static NSString *const appSecretStr = @"46a77d711606499393bfe2634340e7";

enum downStatus{
    NONE = 0,
    DOWNLOADING = 1,
    DOWNLOADFINISHED = 2,
    DOWNLOADFAILED = 3
};

@interface ZTLCCamera ()
{
    __block enum downStatus m_downStatus[DEV_CHANNEL_MAX*DEV_NUM_MAX];
    
    
}
@property (nonatomic, strong) NSLock         *m_devLock;
@property (nonatomic, strong) LCOpenSDK_Api  *m_hc;
@property (nonatomic, strong) NSMutableArray *m_devList;

@property (nonatomic, strong) NSMutableData    *m_picTmp;
@property (nonatomic, assign) BOOL             m_looping;
@property (nonatomic, assign) NSInteger        m_iPos;
@property (nonatomic, assign) NSInteger        m_downloadingPos;

@property (nonatomic, strong) NSURL *m_httpUrl;
@property (nonatomic, strong) NSMutableURLRequest *m_req;
@property (nonatomic, strong) NSURLConnection     *m_conn;
@property (nonatomic, strong) NSLock           *m_downStatusLock;
@property (nonatomic, copy)   NSString *token;
@end
@implementation ZTLCCamera

- (void)reciveStatus:(uint32_t)gatewayApsn
          deviceLuid:(uint64_t)deviceLuid
         triggerApsn:(uint32_t)triggerApsn
         triggerLuid:(uint64_t)triggerLuid
           timestamp:(uint32_t)timestamp
            statusID:(uint8_t)statusID
                data:(XAITLV *)data
           isHistory:(BOOL)isHistory
{
    if (!data) {
        NSLog(@"reciveStatus 收到的数据为空");
        return;
    }
    [super reciveStatus:gatewayApsn deviceLuid:deviceLuid triggerApsn:triggerApsn triggerLuid:triggerLuid timestamp:timestamp statusID:statusID data:data isHistory:isHistory];
    switch (statusID)
    {
        case 0x01:
        {
            NSString* str  = [[NSString alloc]initWithBytes:[data getPayloadbyte] length:data.payloadlen encoding:NSUTF8StringEncoding];
            if (str.length == 0)
            {
                return;
            }
            if (isHistory) {
        
            }
            else
            {
                NSArray* strArray = [str componentsSeparatedByString:@"."];
                if (strArray.count < 2) {
                    return;
                }
                self.strPhoneNum = strArray[0];
                self.strSerial = strArray[1] ;
                NSCharacterSet* characterSet = [NSCharacterSet characterSetWithCharactersInString:@"\0"];
                self.strSerial =  [self.strSerial stringByTrimmingCharactersInSet:characterSet];
                if (self.cameraDeviceInfo == nil)
                {
                    [self loadcameraDeviceInfo];
                }
                else
                {
                    [kDataManager deviceRefreshCallBackWithType:DeviceCallbackTypeStatus];
                }
            }
        }
            break;
        default:
            break;
    }
}

- (BOOL)unbundling
{
    BOOL result = false;
    if (self.cameraDeviceInfo) {
        NSString * m_strDevSelected = (self.cameraDeviceInfo.devInfo)->ID;
        NSString * destOut;
        RestApiService * restApiService = [RestApiService shareMyInstance];
        BOOL ret =  [restApiService unBindDevice:m_strDevSelected Desc:&destOut];
        if (ret ) {
            debugLogInfo(@"摄像头解绑成功！");
        }else{
            debugLogInfo(@"摄像头解绑失败！");
        }
        result = ret;
    }
    return result;
}

- (void) reciveStatus:(XAIPKTStatus* __nullable)pktStatus
{
    [super reciveStatus:pktStatus];
    XAIFormatDataCount* formatDataCount = [XAIFormatDataCount format:[pktStatus getPayloadbyte] length:pktStatus.payloadlen];
    XAITLV *tlv = [formatDataCount  getTLVAtIndex:0];
    switch (pktStatus.oprId)
    {
        case 0x01:
        {
            NSString *str = [[NSString alloc]initWithBytes:[tlv getPayloadbyte] length: tlv.payloadlen encoding:NSUTF8StringEncoding];
            debugLogInfo(@" length = %zd camera str = %@",  tlv.payloadlen,str);
            NSArray *strArray = [str componentsSeparatedByString:@"."];
            if (strArray.count != 2) {
                debugLogInfo(@"摄像头名字格式不对  %@",str);
                return;
            }
            self.strPhoneNum = strArray[0];
            self.strSerial = [strArray[1] stringByReplacingOccurrencesOfString:@"\0" withString:@""];
           
            if (self.cameraDeviceInfo == nil)
            {
                [self loadcameraDeviceInfo];
            }

            else
            {
                [kDataManager callBack];
            }

        }
            break;
        default:
            break;
    }
}

- (void)loadcameraDeviceInfo
{
    if (self.cameraDeviceInfo == nil)
    {
        __weak typeof(self)weakSelf = self;
        [ZTLCCameraUtil fetchToken:self.strPhoneNum CompletionBlock:^(id returnValue) {
            __strong typeof(weakSelf)strongSelf = weakSelf;
            if (!strongSelf)
            {
                return ;
            }
            strongSelf.token = returnValue;
            [strongSelf loadCameraDevInfo:returnValue];
            [kDataManager callBack];
        } WithFailureBlock:^(NSString *errMsg) {
            NSLog(@"errMsg = %@",errMsg);
        }];
    }
}
- (void)onEnterDevice:(NSString *)phoneNum
{
    if (phoneNum.length == 0) {
        debugLogInfo(@"摄像头手机号码为空")
        return;
    }
    dispatch_queue_t enter_device = dispatch_queue_create("enter_device", nil);
    dispatch_async(enter_device, ^{
        NSString * acessTok;
        NSString * errCode;
        NSString * errMsg;
        OpenApiService *openApi = [[OpenApiService alloc] init];
        NSInteger ret = [openApi getUserToken:svrStr port:iPort appId:appIdStr appSecret:appSecretStr phone:phoneNum token:&acessTok errcode:&errCode errmsg:&errMsg];
        dispatch_async(dispatch_get_main_queue(), ^{
            if (ret < 0)
            {
                if (![errCode isEqualToString:@"TK1004"])
                {
                    debugLogInfo(@"当前手机号未与您的应用绑定，请点击\"用户绑定\"按扭进行用户绑定操作。");
                    return;
                }
                if (nil != errMsg)
                {
                    debugLogInfo(@"%@",[errMsg mutableCopy]);
                    return;
                }
            }
            else
            {
                NSString * userTokStr = [acessTok mutableCopy];
                self.token = userTokStr;
                debugLogInfo(@"userToken=%@",userTokStr);
                [self loadCameraDevInfo:userTokStr];
            }
        });
    });
}

- (void)loadCameraDevInfo:(NSString *)token
{
    NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"cert" ofType:@"pem"];
    self.m_hc = [[LCOpenSDK_Api shareMyInstance]initOpenApi:svrStr port:iPort CA_PATH:cerPath];
    RestApiService * restApiService = [RestApiService shareMyInstance];
    self.m_devList = [[NSMutableArray alloc]init];
    if (nil != self.m_hc && nil != token)
    {
        [restApiService initComponent:self.m_hc Token:token];
    }
    else
    {
        debugLogInfo(@" m_hc or m_accessToken is nil");
        return;
    }
    __weak typeof(self)weakSelf = self;
    dispatch_queue_t get_devlist = dispatch_queue_create("get_devlist", nil);
    dispatch_async(get_devlist, ^{
        __strong typeof(weakSelf)strongSelf = weakSelf;
        if (!strongSelf)
        {
            return ;
        }
        if ([restApiService getDevList:strongSelf.m_devList Begin:DEV_BEGIN End:DEV_END ])
        {
            if (0 == strongSelf.m_devList.count)
            {
                debugLogInfo(@"getDevList NULL");
                return;
            }
            for (int i = 0; i < DEV_CHANNEL_MAX*DEV_NUM_MAX;i++)
            {
                m_downStatus[i] = NONE;
            }
            self.m_downStatusLock = [[NSLock alloc]init];
            self.m_devLock = [[NSLock alloc]init];
            self.cameraDeviceInfo =  [self findMyCarmera:self.m_devList];
            NSInteger iDevKey = [self locateDevKeyIndex:self.cameraDeviceInfo.index];
            NSInteger iChnKey = [self locateDevChannelKeyIndex:self.cameraDeviceInfo.index];
            if (iDevKey >= self.m_devList.count)
            {
                return;
            }
            NSString *picUrl = ((DeviceInfo *)[self.m_devList objectAtIndex:iDevKey])->channelPic[iChnKey];
            if (picUrl.length == 0) {
                return;
            }
            self.cameraDeviceInfo.picUrl = [NSString stringWithString:picUrl];
        }
        else
        {
            debugLogInfo(@"网络超时");
        }
    });
    

    
}

- (CameraDeviceInfo *)findMyCarmera:(NSArray *)devList
{
    NSInteger index = 0;
    CameraDeviceInfo *cameralDevInfo  = nil;
    for (DeviceInfo *info in devList)
    {
        if ([info->ID isEqualToString:self.strSerial] )
        {
            cameralDevInfo = [[CameraDeviceInfo alloc]init];
            cameralDevInfo.name = self.name;
            cameralDevInfo.token = self.token;
            cameralDevInfo.devInfo = info;
            cameralDevInfo.index = index;
            cameralDevInfo.m_hc = self.m_hc;
            cameralDevInfo.phoneNum = self.strPhoneNum;
            break;
        }
        index++;
    }
    return cameralDevInfo;
}

-(void) downloadThread
{
    self.m_iPos = 0;
    self.m_downloadingPos = -1;
    int j;
    while (self.m_looping)
    {
        BOOL bNeedDown = YES;
        NSString *picUrl;
        [self.m_devLock lock];
        [self.m_downStatusLock lock];
        do{
            picUrl = nil;
            NSInteger iDevKey = [self locateDevKeyIndex:self.m_iPos];
            NSInteger iChnKey = [self locateDevChannelKeyIndex:self.m_iPos];
            if (iDevKey < 0 || iChnKey < 0)
            {
                bNeedDown = NO;
                self.m_iPos = (self.m_iPos+1)%(DEV_CHANNEL_MAX*DEV_NUM_MAX);
                break;
            }
            for (j = 0; j < DEV_CHANNEL_MAX*DEV_NUM_MAX;j++)
            {
                if (DOWNLOADING == m_downStatus[j])
                {
                    break;
                }
            }
            if (j < DEV_CHANNEL_MAX*DEV_NUM_MAX)
            {
                bNeedDown = NO;
                break;
            }
            if (m_downStatus[self.m_iPos] != NONE)
            {
                bNeedDown = NO;
                self.m_iPos = (self.m_iPos+1)%(DEV_CHANNEL_MAX*DEV_NUM_MAX);
                break;
            }
            
            picUrl = [NSString stringWithString:((DeviceInfo *)[self.m_devList objectAtIndex:iDevKey])->channelPic[iChnKey]];
            
            
            [self.m_devLock lock];
            [self.m_downStatusLock lock];
        }while (0);
        
        //        if (NO == bNeedDown)
        //        {
        //            [self.m_downStatusLock unlock];
        //            [self.m_devLock unlock];
        //            usleep(10*1000);
        //            continue;
        //        }
        //        //download
        //        self.m_httpUrl = [NSURL URLWithString:picUrl];
        //        [_m_downStatusLock lock];
        //        m_downStatus[self.m_iPos] = DOWNLOADING;
        //        [_m_downStatusLock unlock];
        //        self.m_downloadingPos = self.m_iPos;
        //        dispatch_async(dispatch_get_main_queue(), ^{
        //            self.m_req = [[NSMutableURLRequest alloc]init];
        //            [self.m_req setURL:self.m_httpUrl];
        //            [self.m_req setHTTPMethod:@"GET"];
        //            [self.m_req setTimeoutInterval:10];
        //            self.m_conn = [NSURLConnection connectionWithRequest:self.m_req delegate:self];
        //            debugLogInfo(@"downloading task[%ld] now downloading[%@]",(long)self.m_downloadingPos,self.m_req);
        //        });
        //        self.m_iPos = (self.m_iPos+1)%(DEV_CHANNEL_MAX*DEV_NUM_MAX);
        //        [self.m_downStatusLock unlock];
        //        [self.m_devLock unlock];
        //        //end
        //        usleep(20*1000);
    }
}
-(void) destroyThread
{
    self.m_looping = NO;
    usleep(40*1000);
}

-(void) connection:(NSURLConnection*)connection didReceiveData:(NSData *)data
{
    if (connection != self.m_conn)
    {
        return;
    }
    [self.m_picTmp appendData:data];
    
}

-(void) connectionDidFinishLoading:(NSURLConnection*)connection
{
    if (connection != self.m_conn)
    {
        return;
    }
    if (self.m_downloadingPos < 0)
    {
        NSLog(@"connectionDidFinishLoading m_downloadingPos[%ld]",(long)self.m_downloadingPos);
        return;
    }
    DataManager *dataManager = [DataManager sharedManager];
    dataManager->m_picDataArray[self.m_downloadingPos] = [NSData dataWithData:self.m_picTmp];
    [self.m_picTmp setLength:0];
    [self.m_downStatusLock lock];
    m_downStatus[self.m_downloadingPos] = DOWNLOADFINISHED;
    [self.m_downStatusLock unlock];
    [self findMyCarmera:self.m_devList];
    
}

-(void) connection:(NSURLConnection*)connection didFailWithError:(NSError *)error
{
    if (connection != self.m_conn)
    {
        return;
    }
    if(self.m_downloadingPos < 0)
    {
        return;
    }
    debugLogInfo(@"download failed[%@]",error);
    [self.m_picTmp setLength:0];
    [self.m_downStatusLock lock];
    m_downStatus[self.m_downloadingPos] = DOWNLOADFAILED;
    [self.m_downStatusLock unlock];
    [self findMyCarmera:self.m_devList];
    
}

-(void) connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse *)response
{
    if (connection != self.m_conn)
    {
        return;
    }
    [self.m_picTmp setLength:0];
}

- (void) freeView:(UIView* )view
{
    view = nil;
}-(NSInteger) locateDevKeyIndex:(NSInteger)index
{
    int iChCount = 0;
    int i = 0;
    for (DeviceInfo * dev in self.m_devList) {
        if (nil == dev->ID) {
            break;
        }
        iChCount += dev->channelSize;
        if (iChCount >= index + 1) {
            break;
        }
        i++;
    }
    return (iChCount >= index+1)?i:-1;
}

-(NSInteger) locateDevChannelKeyIndex:(NSInteger)index
{
    int iChCount = 0;
    int i = 0;
    for (DeviceInfo * dev in self.m_devList) {
        if (nil == dev->ID) {
            break;
        }
        iChCount += dev->channelSize;
        if (iChCount >= index + 1) {
            break;
        }
        i++;
    }
    return (iChCount >= index+1)?(index-iChCount+((DeviceInfo *)[self.m_devList objectAtIndex:i])->channelSize):-1;
}


@end
